package org.example.netty.test.nio.netty.chat.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.example.netty.test.nio.netty.chat.bean.LogoutMessage;
import org.example.netty.test.nio.netty.chat.bean.SystemMessage;
import org.example.netty.test.nio.netty.chat.bean.User;
import org.example.netty.test.nio.netty.chat.common.SystemMessageType;
import org.example.netty.test.nio.netty.chat.session.GlobalContent;
import org.example.netty.test.nio.netty.chat.session.UserSession;
import org.example.netty.test.nio.netty.chat.util.NettyChannelUtil;

import java.util.Objects;

/**
 * @author zp
 * @version 1.0
 * @description: 服务端的心跳监听器
 * @date 2023/5/21 16:57
 */
@Slf4j
public class ServerIdleHandler extends ChannelDuplexHandler {
    /**
     * @param ctx
     * @param evt
     * @description: 如果为IdleStateEvent事件，直接将连接关闭。
     * @author zp
     * @date: 2023/5/21 16:59
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (IdleState.READER_IDLE.equals(idleStateEvent.state())) {
                // 长时间未操作 关闭登出客户端
                Channel channel = ctx.channel();
                UserSession userSession = NettyChannelUtil.getUserSession(channel);
                if (userSession != null) {
                    User user = userSession.getUser();
                    GlobalContent globalContent = GlobalContent.getInstance();
                    // 解绑定
                    globalContent.unbind(user.getUserId(), user.getUserName());
                    // 删除channel里面的数据
                    NettyChannelUtil.removeUserSession(channel);
                }
                log.info("长时间未操作 自动释放连接");
                ctx.close();
            } else {
                super.userEventTriggered(ctx, evt);
            }
        }
    }
}
